﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Helpers;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace Eneta.Portal.Companies
{
    public class CompanyDetailsPage : PublishingLayoutPage
    {
        protected Label modifiedLabel;
        //protected Label addressLabel;
        protected Label streetLabel;
        protected Label zipLabel;
        protected Label cityLabel;

        //protected Label phoneLabel;
        //protected HtmlAnchor emailLink;
        protected HtmlAnchor homePageField;
        protected Label employeesLabel;
        protected Label certifiedLabel;
        protected HtmlAnchor createdLink;
        protected Image logo;
        protected HtmlControl logoContainer;
        protected HtmlImage logoImage;
        protected HtmlAnchor logoLink;
        protected Label descrLabel;
        protected HtmlImage partnerImage;
        protected Repeater officeRepeater;
        protected HtmlGenericControl VCardContainer;
        protected HtmlAnchor VCardLink;

        protected Label contactLabel;
        protected HtmlAnchor contactEmailLink;
        protected Label contactPhoneLabel;

        protected HtmlAnchor profileLink;
        protected HtmlImage profileImage;
        protected HtmlGenericControl profileOwnerLabel;
        protected HtmlGenericControl ProfileNavContainer;

        protected Label topicsLabel;
        protected Label productsLabel;
        protected Label AddCompanyUserField;
        protected HtmlGenericControl AddCompanyContainer;
        protected HtmlGenericControl announcementHolder;

        protected Repeater announcementsRepeater;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            officeRepeater.ItemDataBound += OfficeRepeaterItemDataBound;
            announcementsRepeater.ItemDataBound += announcementsRepeater_ItemDataBound;
        }

        void announcementsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var item = (AnnouncementDto) e.Item.DataItem;
            var dateField = (HtmlGenericControl) e.Item.FindControl("announcementDate");
            var titleLink = (HtmlAnchor) e.Item.FindControl("_announcementTitle");
            var auhtorLink = (HtmlAnchor) e.Item.FindControl("_profileLink");

            dateField.InnerText = item.Created.ToString("dd.MM.yyyy");
            titleLink.HRef = "/uudised/teated/AnnouncementView.aspx?ID=" + item.Id;
            titleLink.InnerText = item.Title;
            auhtorLink.HRef = "/profile.aspx?ID=" + item.OwnerProfileId;
            auhtorLink.InnerText = item.OwnerUserName;
        }

        protected void OfficeRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var label = (Label)e.Item.FindControl("officeNameLabel");
            label.ID = "officeNameLabel_" + e.Item.ItemIndex;
            label.Text = e.Item.DataItem.ToString();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            
            int itemId;
            var repository = new CompanyRepository(SPContext.Current.Web);
            CompanyDto item = null; 

            var sec = new SPSecurity.CodeToRunElevated(delegate
                  {
                      if (SPContext.Current.ListItem != null)
                      {
                          itemId = SPContext.Current.ListItem.ID;
                          item = repository.GetCompanyById(itemId);
                          return;
                      }

                      if (int.TryParse(Request.QueryString["id"], out itemId))
                      {
                          item = repository.GetCompanyById(itemId);
                          return;
                      }
                  }                                         
                );
            SPSecurity.RunWithElevatedPrivileges(sec);

            if(item == null)
            {
                Response.Write("ITEM ON NULL!");
                return;
            }
            
            VCardContainer.Visible = CanShowVCardButton(item);

            var act = Request.QueryString["act"] ?? string.Empty;

            if (act.ToLower() == "vcard" && VCardContainer.Visible)
            {
                OutputVCard();
                Response.End();
            }

            ProfileNavContainer.Visible = (SPContext.Current.Web.CurrentUser != null);
            if (SPContext.Current.Web.CurrentUser != null)
            {
                AddCompanyContainer.Visible = !SPContext.Current.Web.CurrentUser.HasCompany();
                if (AddCompanyContainer.Visible)
                    AddCompanyUserField.Text = SPContext.Current.Web.CurrentUser.Name;
            }
            else
                AddCompanyContainer.Visible = false;
            modifiedLabel.Text = item.Modified.ToShortDateString(); // DateTime.Parse(item["Modified"].ToString()).ToShortDateString();

            VCardLink.HRef = Request.FilePath + "?act=vcard";
            streetLabel.Text = item.Street;
            zipLabel.Text = item.Zip;
            cityLabel.Text = item.City;
            if (!string.IsNullOrEmpty(item.HomePage))
                homePageField.HRef = item.HomePage;
            else
                homePageField.Visible = false;

            employeesLabel.Text = item.Employees;
            if (!string.IsNullOrEmpty(item.CertifiedEmployees))
                certifiedLabel.Text = item.CertifiedEmployees;
            else
                certifiedLabel.Text = "0";

            descrLabel.Text = item.Description;
            descrLabel.Text = descrLabel.Text.Nl2Br();
            descrLabel.Text = RegExHelper.DetectAndReplaceUrls(descrLabel.Text);
            
            Logger.LogInfo("OnLoad(): Before logo",GetType().ToString());
            
            var logoName = item.FileName.Replace(".aspx", ".png");
            var logoUrl = "/SiteCollectionImages/firmad/" + logoName;
            var logoFile = SPContext.Current.Site.RootWeb.GetFile(logoUrl);
            logoContainer.Visible = false;
            if (logoFile.Exists)
            {
                Logger.LogInfo("OnLoad(): Before logo container",GetType().ToString());
                logoContainer.Visible = logoFile.Exists;
                //Log("<!--logo name: " + logoUrl + "\r\n" + logoFile.Exists + "\r\n-->");
                if (logoFile.Exists)
                {
                    logoLink.HRef = homePageField.HRef;
                    logoImage.Src = logoUrl;
                    logoImage.Alt = item.Title;
                    logoLink.Title = item.Title;
                }
            }
            else
                Logger.LogInfo("OnLoad(): logoFile is null", GetType().ToString());
            
            contactLabel.Text = item.ContactName;

            if (!string.IsNullOrEmpty(item.ContactPhone))
                contactPhoneLabel.Text = "tel " + item.ContactPhone;

            if (!string.IsNullOrEmpty(item.ContactEmail))
                contactEmailLink.HRef = "mailto:" + item.ContactEmail;
            else
                contactEmailLink.Visible = false;

            partnerImage.Visible = false;
            if (!string.IsNullOrEmpty(item.PartnershipLevel))
            {
                var certPath = "/Style Library/eneta/images/" + item.PartnershipLevel.ToLower().Replace(" ", "-") + "_medium.gif";
                var certFile = SPContext.Current.Site.RootWeb.GetFile(certPath);
                if (certFile.Exists)
                {
                    partnerImage.Src = certPath;
                    if (certPath.ToLower().Contains("kuld") || certPath.ToLower().Contains("gold"))
                        partnerImage.Alt = "Microsoft Gold Certified Partner";
                    else
                        partnerImage.Alt = "Microsoft Certified Partner";
                    partnerImage.Attributes["title"] = partnerImage.Alt;
                    partnerImage.Visible = true;
                }
            }

            var userString = item.AuthorUserName;
            var currentUserString = string.Empty;

            if (SPContext.Current.Web.CurrentUser != null)
                currentUserString = SPContext.Current.Web.CurrentUser.ToString();

            var profileRepository = new UserProfileRepository(SPContext.Current.Web);

            if (!string.IsNullOrEmpty(userString))
            {
                var profile = profileRepository.GetUserProfileById(item.OwnerProfileId);
                if(profile != null)
                    profileImage.Src = profile.UserImage32x32Url; // "/_layouts/enetahandlers/userimagehandler.ashx?size=16&id=" + item.OwnerProfileId.ToString();
                profileLink.HRef = "/profile.aspx?ID=" + item.OwnerProfileId;                
                profileOwnerLabel.InnerText = item.OwnerProfileName;

                if (currentUserString == userString)
                {
                    profileOwnerLabel.InnerText = "Sina";
                    profileLink.Title = "Sinu profiil";
                }
                else
                {
                    profileOwnerLabel.InnerText = item.OwnerProfileName;
                    profileLink.Title = "Vaata profiili";
                }
            }

            if (item.Offices != null)
            {
                var officesList = new List<string>();

                foreach (var office in item.Offices)
                    officesList.Add(office.Title);

                var officesArray = officesList.ToArray();
                Array.Sort(officesArray);
                officeRepeater.DataSource = officesArray;
                officeRepeater.DataBind();
            }

            var annRepository = new AnnouncementRepository(SPContext.Current.Web);
            var onlyApproved = true;
            if (SPContext.Current.Web.CurrentUser != null)
                if (SPContext.Current.Web.CurrentUser.IsSiteAdmin)
                    onlyApproved = false;

            var announcements = annRepository.GetAnnouncementsByCompany(item.Id, onlyApproved);
            announcementHolder.Visible = (announcements.Count > 0);
            if (announcementHolder.Visible)
            {
                announcementsRepeater.DataSource = announcements;
                announcementsRepeater.DataBind();
            }
            BindIo(item.Id);
        }

        private void BindIo(int id)
        {
            var topicList = new List<string>();
            var productList = new List<string>();

            var list = SPContext.Current.Web.Lists["IOCompany"];
            var topics = SPContext.Current.Web.Lists["IOTopic"];
            var queryString = "<Where><Eq><FieldRef Name='Company' LookupId='True' /><Value Type='Lookup'>{0}</Value></Eq></Where>";
            queryString = string.Format(queryString, id);

            var query = new SPQuery();
            query.Query = queryString;

            var items = list.GetItems(query);

            foreach (SPListItem item in items)
            {
                var level3Value = item["IOTopic"];
                if (level3Value == null)
                    continue;

                var level3Lookups = new SPFieldLookupValueCollection(level3Value.ToString());
                foreach (var level3Lookup in level3Lookups)
                    if (!topicList.Contains(level3Lookup.LookupValue))
                    {
                        topicList.Add(level3Lookup.LookupValue);

                        Logger.LogInfo("BindIo(): CompanyDetailsPage: Searching products",GetType().ToString());
                        queryString = "<Where><Eq><FieldRef Name='ID' /><Value Type='Integer'>{0}</Value></Eq></Where>";
                        queryString = string.Format(queryString, level3Lookup.LookupId);
                        query = new SPQuery();
                        query.Query = queryString;

                        var topicItems = topics.GetItems(query);
                        if (topicItems == null)
                        {
                            Logger.LogInfo("BindIo(): CompanyDetailsPage: topicItems==null",GetType().ToString());
                            continue;
                        }
                        if (topicItems.Count == 0)
                        {
                            Logger.LogInfo("BindIo(): CompanyDetailsPage: topicItems.Count==0",GetType().ToString());
                            continue;
                        }
                        var topicItem = topicItems[0];

                        var productsValue = topicItem["IOProducts"];
                        if (productsValue == null)
                        {
                            Logger.LogInfo("BindIo(): CompanyDetailsPage: productsValue==null",GetType().ToString());
                            continue;
                        }
                        Logger.LogInfo("BindIo(): CompanyDetailsPage: productsValue==" + productsValue,GetType().ToString());
                        var productsLookup = new SPFieldLookupValueCollection(productsValue.ToString());
                        Logger.LogInfo("BindIo(): CompanyDetailsPage: productsLookupCount==" + productsLookup.Count, GetType().ToString());
                        foreach (var product in productsLookup)
                        {
                            queryString = "<Where><Eq><FieldRef Name='ID' /><Value Type='Integer'>{0}</Value></Eq></Where>";
                            queryString = string.Format(queryString, product.LookupId);
                            query = new SPQuery();
                            query.Query = queryString;

                            var productItem = SPContext.Current.Web.Lists["IOProducts"].GetItems(query)[0];
                            var productText = product.LookupValue;
                            var link = productItem[productItem.Fields.GetFieldByInternalName("ProductLink").Id];

                            if (link != null)
                            {
                                var linkValue = new SPFieldUrlValue(link.ToString());
                                productText = "<a href=\"" + linkValue.Url + "\">" + productText + "</a>";
                            }

                            if (productList.Contains(productText))
                                continue;


                            productList.Add(productText);
                        }
                    }
            }
            var topicArray = topicList.ToArray();
            var prodArray = productList.ToArray();

            var topicsString = string.Join(", ", topicArray);
            var prodString = string.Join(", ", prodArray);

            topicsLabel.Text = topicsString;
            productsLabel.Text = prodString;
        }

        private bool CanShowVCardButton(CompanyDto item)
        {
            return !string.IsNullOrEmpty(item.ContactName); //(item["Kontaktisik"] != null);
            //&& (item["KontaktisikuTelefon"] != null)
            //&& (item["KontaktisikuEmail"] != null);
        }

        private void OutputVCard()
        {
            var siteId = SPContext.Current.Site.ID;
            var webId = SPContext.Current.Web.ID;
            var listId = SPContext.Current.ListItem.ParentList.ID;
            var itemId = SPContext.Current.ListItem.ID;

            var sec = new SPSecurity.CodeToRunElevated(delegate
            {
                using (var site = new SPSite(siteId))
                {
                    using (var web = site.AllWebs[webId])
                    {
                        var list = web.Lists[listId];
                        var item = list.GetItemById(itemId);
                        Response.ContentType = "text/vcard";                        

                        Response.AddHeader("Content-Disposition", "attachment;filename=" + item.Title.Replace(" ", "-") + ".vcf");
                        var cardBuffer = new StringBuilder();
                        cardBuffer.Append("BEGIN:VCARD\r\n");
                        cardBuffer.Append("VERSION:2.1\r\n");
                        cardBuffer.Append("N:" + item["Kontaktisik"] + "\r\n");
                        cardBuffer.Append("ORG:" + item.Title + "\r\n");
                        cardBuffer.Append("TEL;WORK;VOICE:" + item["KontaktisikuTelefon"] + "\r\n");
                        var address = item["Tanav"] + ";" + item["WorkCity"] + ";;" + item["Postiindeks"];
                        cardBuffer.Append("ADR;WORK:;;" + address + "\r\n");
                        cardBuffer.Append("EMAIL;PREF;INTERNET:" + item["KontaktisikuEmail"] + "\r\n");
                        if (item["WebPage"] != null)
                        {
                            var url = new SPFieldUrlValue(item["WebPage"].ToString());
                            cardBuffer.Append("URL;WORK:" + url.Url + "\r\n");
                        }
                        cardBuffer.Append("END:VCARD");
                        var bytes = cardBuffer.ToString().ToWindows1257();
                        Response.OutputStream.Write(bytes, 0, bytes.Length);
                    }
                }
            });
            SPSecurity.RunWithElevatedPrivileges(sec);
        }
    }
}
